package com.yonyou.crm.csns.im.ctrl;

import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springside.modules.nosql.redis.JedisTemplate;

import com.yonyou.crm.common.exception.CrmMessageException;
import com.yonyou.crm.common.http.client.CrmHttpClient;
import com.yonyou.crm.common.http.client.CrmResponse;
import com.yonyou.crm.common.rest.constant.HttpCodeConstant;
import com.yonyou.crm.common.rest.constant.PCCodeConstant;
import com.yonyou.crm.csns.im.constant.ImConstant;
import com.yonyou.crm.csns.im.rmitf.IImRmService;
import com.yonyou.crm.sys.user.entity.UserVO;

@RestController
@RequestMapping(value="/csns/im")
public class ImCtrl {
	
	private final static String ImBaseDir = "https://im.yyuap.com/";
	private final static String AppTokenPrefix = "IMAppToken:";
	
	/**
	 * im的apptoken有效期为24小时
	 * 为保持数据同步，本地有效期设置为23小时
	 */
	private final static int ExpireSeconds = 23*60*60;
	
	@Autowired
	private JedisTemplate jedisTemplate;
	
	@Autowired
	private IImRmService service;
	
	/**
	 * 修改用户vcard信息
	 * 修改用户信息时同步到IM远程
	 * @param user
	 * @return
	 * @throws CrmMessageException
	 */
	public CrmResponse updateVcard(UserVO user) throws CrmMessageException {
		
		Long userId = user.getId();
		if (userId == null) {
			throw new CrmMessageException(PCCodeConstant.ServerError ,"用户主键不能为空");
		}

		Map<String, Object> imMap = service.getImInfo(new Long(userId));
		
		String appToken = getAppToken(imMap);
		
		String eptId = (String) imMap.get(ImConstant.EptId);
		String appId = (String) imMap.get(ImConstant.AppId);
		String url = ImBaseDir + "sysadmin/rest/remotevcard/"+ eptId +"/"+ appId +"/updateVcard?token=" + appToken;

		JSONObject paramObj = new JSONObject();
		paramObj.put("username", userId);//用户名
		paramObj.put("nickname", user.getName());//昵称
		paramObj.put("email", user.getEmail());//邮箱
		paramObj.put("photo",  user.getPortraitId());//头像
		paramObj.put("mobile", user.getPhone());//手机号
		paramObj.put("password", "");//密码
		paramObj.put("orgId", "");//组织id
		paramObj.put("position", "");//职位
		paramObj.put("location", "");//办公地点
		paramObj.put("number", "");//工号
		paramObj.put("gender", "");//性别
		paramObj.put("remarks", "");//备注
		paramObj.put("telephone", "");//分机号
		
		return CrmHttpClient.put(url, paramObj);
	}
	
	/**
	 * 向IM发送获取应用token请求
	 * @param imMap
	 * @return
	 * @throws CrmMessageException
	 */
	private CrmResponse sendAppTokenRequest(Map<String, Object> imMap) throws CrmMessageException {
		
		if (imMap == null || imMap.size() == 0) {
			throw new CrmMessageException(PCCodeConstant.ServerError, "获取IM认证信息失败");
		}

		String eptId = (String) imMap.get(ImConstant.EptId);
		String appId = (String) imMap.get(ImConstant.AppId);
		String url = ImBaseDir + "sysadmin/rest/"+ eptId +"/"+ appId +"/token";
				
		JSONObject paramObj = new JSONObject();
		paramObj.put(ImConstant.ClientId, imMap.get(ImConstant.ClientId));
		paramObj.put(ImConstant.ClientSecret, imMap.get(ImConstant.ClientSecret));
				
		return CrmHttpClient.post(url, paramObj);
	}
	
	/**
	 * 获得应用token字符串
	 * @param imMap
	 * @return
	 * @throws CrmMessageException
	 */
	private String getAppToken(Map<String, Object> imMap) throws CrmMessageException {

		String tokenKey = AppTokenPrefix + imMap.get("tenantId");
		
		//从redis中获取
		String appToken = jedisTemplate.get(tokenKey);
		if (StringUtils.isNotBlank(appToken)) {
			return appToken;
		}

		//从im远程获取
		CrmResponse cResp = sendAppTokenRequest(imMap);
		if (cResp.getCode() != HttpCodeConstant.OK) {
			throw new CrmMessageException(cResp.getData());
		}
		
		JSONObject atObj = JSONObject.fromObject(cResp.getData());
		String token = "";
		if (atObj != null && atObj.containsKey("token")) {
			token =  (String) atObj.get("token");
			//存储到redis，过期时间23小时
			jedisTemplate.setnxex(tokenKey, token, ExpireSeconds);
		}

		return token;
	}

}

